const express = require("express");
const router = express.Router();
const Response = require("../utils/Response.js");
const fs = require("fs");

// 引入mysql连接池
const pool = require("../utils/db.js");

// 轮播图
router.get('/pic', (req, res, next) => {
	let obj = req.query;
	console.log(obj);
	pool.query('select * from activity_pic', [], (err, result) => {
		if (err) {
			next(err);
			return;
		}
		console.log(result);
		if (result.length === 0) {
			res.send({ code: 201, msg: "失败" });
		} else {
			res.send({ code: 200, msg: "查询成功", data: result });
		}
	});
});

// 活动列表
router.get('/list', (req, res, next) => {
	let obj = req.query;
	console.log(obj);
	pool.query('select * from activity_list', [], (err, result) => {
		if (err) {
			next(err);
			return;
		}
		console.log(result);
		if (result.length === 0) {
			res.send({ code: 201, msg: "查询失败" });
		} else {
			res.send({ code: 200, msg: "查询成功", data: result });
		}
	});
});

// 查询所有活动类型
router.get('/activity_type_all', (req, res, next) => {
	let obj = req.query;
	console.log(obj);
	pool.query('select * from activity_type', [], (err, result) => {
		if (err) {
			next(err);
			return;
		}
		console.log(result);
		if (result.length === 0) {
			res.send({ code: 201, msg: "失败" });
		} else {
			res.send({ code: 200, msg: "查询成功", data: result });
		}
	});
});

// 通过类型id查询活动
router.get('/activity_info', (req, res, next) => {
	let obj = req.query;
	console.log(obj);
	pool.query(`
	select 
	 activity_list.id,
	 activity_list.pic,
	 activity_list.title,
	 activity_list.time,
	 activity_list.number
	from 
		activity_list,activity_type 
	where 
		? and activity_type.id = activity_type_id
	`, [obj], (err, result) => {
		if (err) {
			next(err);
			return;
		}
		console.log(result);
		if (result.length === 0) {
			res.send({ code: 201, msg: "失败" });
		} else {
			res.send({ code: 200, msg: "查询成功", data: result });
		}
	});
});


// 新增活动
router.post("/add", (req, res, next) => {
	let obj = req.body;
	pool.query("insert into activity_list set ?", [obj], (err, result) => {
		if (err) {
			return next(err);
		}
		console.log(result);
		if (result.affectedRows === 0) {
			res.send({ code: 201, msg: '新增失败' })
		} else {
			res.send({ code: 200, msg: '新增成功' })
		}
	});
});
module.exports = router;
